<template>
	<view class="main">
		<view class="class-content">
			<view class="picker-search" style="position: relative; display: flex; align-content: center;">
				<u-search placeholder="搜索宝贝,开启租赁新生活" :show-action="false" :clearabled="false" v-model="keyword"
					@change="searList"></u-search>
				<view v-if="keyword"
					style="position: absolute; right:70rpx; display: flex; align-items: center; top: 50%; transform: translateY(-50%);">
					<uni-icons type="closeempty" size="15" @click="keyword=''"></uni-icons>
				</view>
			</view>
			<recommend v-if="keyword" :imageList="list"></recommend>
		</view>
		<view v-if="!keyword">
			<view class="scroll-container">
				<xSwiperNav :navList='chunkedImageList(imgList)' :path='path' @product="product"></xSwiperNav>
			</view>

			<view v-if="!keyword" class="container">
				<!-- 滚动区域 -->
				<!-- v-for="(item, index) in classifyList" -->
				<scroll-view scroll-y class="nav-menu menu-scroll-view" scroll-with-animation :scroll-top="scrollTop"
					:scroll-into-view="itemId">
					<view v-for="(item, index) in classifyList" :key="index" class="menu-item lee-tab-item" :style="{
							borderTopLeftRadius: index === 0 ? '40rpx' : 0,
							color: 'black'
						}" @tap.stop="swichMenu(index, item)">
						<view class="border-le" :style="{
								borderLeft: index == activeIndex ? '10rpx solid #1677FF' : 'none'
							}"></view>
						{{ item.name }}
					</view>
				</scroll-view>

				<scroll-view :scroll-top="scrollRightTop" scroll-y scroll-with-animation @scroll="rightScroll">
					<view class="right-top">
						<view class="top">
							<view class="top-for" @click="show(item)" style="font-size: 25rpx"
								v-for="(item, index) in ['综合', '价格']">
								<text>{{ item }}</text>
								<view v-if="item !== '筛选'">
									<u-icon name="arrow-up-fill" size="7" @click="up(item, index)"
										:color="index == tindex ? '#1677FF' : ''"></u-icon>
									<u-icon name="arrow-down-fill" size="7" @click="down(item, index)"
										:color="index == tindex2 ? '#1677FF' : ''"></u-icon>
								</view>
								<view v-else>
									<u-icon name="arrow-down" size="13"></u-icon>
								</view>
							</view>
							<!-- <view class="top-for">
								<text>筛选</text>
								<view>
									<u-icon name="arrow-down" size="13"></u-icon>
								</view>
							</view> -->
						</view>
					</view>

					<view class="nav-content">
						<!-- <view class="rightDataBox" style="width: 100%" v-for="(items, index) in classifyList" :key="index" :id="'item' + index"> -->
						<view class="rightDataBox"
							style="width: 100%;overflow-y: scroll; padding-top: 20rpx; height: 50vh;">

							<view class="body-list" @click="to(item)"
								v-for="(item, i) in classifyList[activeIndex].classify" :key="i">

								<view class="orderInfo">
									<image style="width: 185rpx; height: 166rpx; margin-right: 10rpx"
										:src="path + item.mainImage" mode="scaleToFill"></image>
									<view class="info">
										<view class="infoname">
											<view class="name" style="color: black">{{ item.description }}</view>
										</view>
										<view>
											<!-- <text class="tag">99新</text> -->
										</view>
										<view class="price">
											<text class="price-text">
												{{
													item.leaseGoodSkus[0].leaseRentalRules[0].everydayPrice == null
														? '无标价'
														: item.leaseGoodSkus[0].leaseRentalRules[0].everydayPrice
												}}
												<span>/天</span>
											</text>
											<button>立即下单</button>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 	<view v-else-if="rightData.length > 0">
							<view class="rightDataBox" style="width: 100%" v-for="(items, index) in rightData" :key="index" :id="'item' + index">
								<u-divider :text="items.name" :dashed="true"></u-divider>
								<view v-if="items.children == null" class="common-no-data">
									<image class="no-data-img" :src="baseImgUrl + 'img_no_project.png'" alt="" />
								</view>
							</view>
							<view class="rightDataBox1" :style="{ height: funMainHeight }" style="width: 100%">
								<u-divider text="已经到底啦~~" :dashed="true"></u-divider>
							</view>
						</view>
						<view v-else class="common-no-data">
							<image class="no-data-img" :src="baseImgUrl + 'img_no_project.png'" alt="" />
							<view class="text">暂无项目</view>
						</view> -->
				</scroll-view>
			</view>

			<u-popup :show="showPicker" v-model="price" mode="right" @close="pickerClose">
				<view class="confrim">
					<view class="confrim-brand">
						<text class="brand-name">品牌</text>
						<view class="brand-list">
							<view v-for="(item, index) in brandClass.brand" style="color: black"
								@click="brandIndexClick(index, item)">
								<text style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
									:class="brandIndex == index ? 'brand-at' : ''">{{ item.name }}</text>
							</view>
						</view>
					</view>
					<view class="confrim-brand">
						<text class="brand-name">最低租期</text>
						<view class="brand-list">
							<view v-for="(item, index) in brandClass.month" @click="leaseIndexClick(index, item)">
								<text :class="leaseIndex == index ? 'brand-at' : ''">{{ item }}</text>
							</view>
						</view>
					</view>

					<view class="price">
						<input type="text" v-model="price.min" placeholder="最低价" />
						<span>——</span>
						<input type="text" v-model="price.max" placeholder="最高价" />
					</view>
					<view class="confrim-btn">
						<button class="botton" @click="onCancel()"
							style="background-color: #eaeaea; color: #aaaaaa">重置</button>
						<button class="botton" @click="onConfirm()">确定</button>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import recommend from '@/subPages/components/recommend.vue';
	import {
		data
	} from '../uni_modules/uview-ui/libs/mixin/mixin';
	import main from '../api/main.js';
	import api from '../api/index.js';
	import xSwiperNav from '@/components/x-swiper-nav/x-swiper-nav.vue'
	export default {
		components: {
			xSwiperNav
		},
		data() {
			return {
				tindex: null,
				tindex2: null,
				classifyList: [],
				path: api.getPath(),
				activeIndex: 0,
				scrollTop: 0, //tab标题的滚动条位置
				oldScrollTop: 0, // tab标题的滚动条旧位置
				scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
				arr: [], // 储存距离顶部高度的数组
				menuHeight: 0, // 左边菜单的高度
				menuItemHeight: 0, // 左边菜单item的高度
				mainHeight: '',
				list: [],
				showPicker: false, //筛选框开关
				currentIndex: 0, //分类一级定位下标
				brandIndex: 0, //品牌定位
				leaseIndex: 0, //最低租期定位
				keyword: '', //搜索内容绑定
				price: {
					max: null,
					min: null
				},
				brandClass: {
					brand: ['无人机', '佳能', '佳能', '佳能', '佳能', '佳能', '尼康', '尼康']
				},
				imgList: [],
				sift: [],
				parmse: {
					classifyId: null
				}
			};
		},
		components: {
			recommend
		},
		onLoad() {
			// this.mainHeight = this.$store.getters.heightData.noTabMainHeight;
		},
		onShow() {
			this.getClassList();
		},
		methods: {
			up(item, index) {
				console.log(item);
				this.tindex2 = null;
				this.tindex = index;
				this.sort2(this.classifyList[this.activeIndex]);
			},
			down(item, index) {
				console.log(item);
				this.tindex = null;
				this.tindex2 = index;
				//排序数组

				this.sort(this.classifyList[this.activeIndex]);
			},
			sort(arr) {
				let sArr = arr.classify.sort((a, b) => b.leaseGoodSkus[0].leaseRentalRules[0].everydayPrice - a
					.leaseGoodSkus[0].leaseRentalRules[0].everydayPrice);
				console.log(sArr);
			},
			sort2(arr) {
				let sArr = arr.classify.sort((a, b) => a.leaseGoodSkus[0].leaseRentalRules[0].everydayPrice - b
					.leaseGoodSkus[0].leaseRentalRules[0].everydayPrice);
				console.log(sArr);
			},
			show(item) {
				if (item == '筛选') {
					this.showPicker = true;
					this.brandClass.brand = this.classifyList;
					console.log(this.brandClass);
				}
			},
			to(item) {
				uni.navigateTo({
					url: '/subPages/main/commodity?id=' + item.id
				});
				//console.log(item)
			},
			searList() {
				let _this = this;
				let Inputdata = {
					productName: _this.keyword,
					pageNo: _this.pageNo,
					pageSize: _this.pageSize
				};
				console.log('dasd', Inputdata);
				main.getList(Inputdata)
					.then((data) => {
						_this.list = data.rows;
						_this.total = data.total;
					})
					.catch((erro) => {
						console.log(erro);
					});
			},
			chunkedImageList(list) {
				const chunkSize = 10;
				const chunks = [];

				for (let i = 0; i < list.length; i += chunkSize) {
					chunks.push(list.slice(i, i + chunkSize));
				}

				return chunks;
			},
			getClassList() {
				main.getGoodsClass()
					.then((data) => {
						console.log('获取分类列表', data);
						this.imgList = data.rows;
						this.product(this.currentIndex);
					})
					.catch((erro) => {
						console.log(erro);
					});
			},
			brandIndexClick(row, item) {
				this.brandIndex = row;
				console.log(item);
				// this.parmse.name = item.name
				this.parmse.classifyId = item.data.id;
			},
			leaseIndexClick(row) {
				this.leaseIndex = row;
			},
			pickerClose() {
				// 筛选框关
				this.showPicker = false;
			},
			product(row) {
				this.classifyList = [];
				this.currentIndex = row;
				//递归子分类
				let arr = [];
				let deep = function(item) {
					console.log(item);

					arr.push(item);

					if (item.leaseGoodCategoryVos) {
						item.leaseGoodCategoryVos.forEach((item, index) => {
							deep(item);
						});
					}
				};
				deep(this.imgList[row]);
				arr.forEach((item, index) => {
					this.classifyList.push({
						name: item.categoryName,
						data: item,
						classifyList: []
					});
				});
				this.swichMenu(0, this.classifyList[0]);
				console.log(arr);
			},
			onConfirm(e) {
				//筛选确定
				let arr = [];
				if (this.parmse.classifyId == null) this.parmse.classifyId = this.classifyList[0].data.id;
				main.getList(this.parmse).then((res) => {
					arr = res.rows.filter((item) => {
						return item.leaseGoodSkus[0].leaseRentalRules[0].everydayPrice >= this.price.min &&
							item.leaseGoodSkus[0].leaseRentalRules[0].everydayPrice <= this.price.max;
					});
					if (!this.price.min || !this.price.max) arr = res.rows;

					this.classifyList[this.activeIndex].classify = arr;
					this.showPicker = false;
				});
				//this.showPicker = false;
				//筛选数据
			},
			onCancel() {
				//筛选重置
				this.showPicker = false;
			},
			getMenuItemTop() {
				new Promise((resolve) => {
					let selectorQuery = uni.createSelectorQuery().in(this);
					selectorQuery
						.selectAll('.rightDataBox')
						.boundingClientRect((rects) => {
							if (!rects.length) {
								setTimeout(() => {
									this.getMenuItemTop();
								}, 10);
								return;
							}
							rects.forEach((rect) => {
								this.arr.push(rect.top - 50);
								console.log('this.arr', this.arr);
								resolve();
							});
						})
						.exec();
				});
			},
			// 设置左边菜单的滚动状态
			async leftMenuStatus(index) {
				this.activeIndex = index;
				// 如果为0，意味着尚未初始化
				if (this.menuHeight == 0 || this.menuItemHeight == 0) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
					await this.getElRect('lee-tab-item', 'menuItemHeight');
				}
				// 将菜单活动item垂直居中
				this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
			},
			// 点击左边的栏目切换
			async swichMenu(index, item) {
				this.activeIndex = index;
				if (!item) return;
				console.log('测试');
				// this.activeIndex = index;
				console.log(item);
				//更据分类获取商品
				main.getGoodsById({
					classifyId: item.data.id
				}).then((res) => {
					// console.log('拿到商品了', res);
					// this.classifyList[index].classify = res.rows;
					this.classifyList.splice(index, 1, {
						...this.classifyList[index],
						classify: res.rows
					});
				});

				// if (this.arr.length == 0) {
				// 	await this.getMenuItemTop();
				// }
				// if (index == this.activeIndex) return;

				// this.scrollRightTop = this.oldScrollTop;
				// this.$nextTick(function () {
				// 	this.scrollRightTop = this.arr[index] - 50;
				// 	this.activeIndex = index;
				// 	this.leftMenuStatus(index);
				// });
			},
			// 获取一个目标元素的高度
			getElRect(elClass, dataVal) {
				new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(this);
					query
						.select('.' + elClass)
						.fields({
								size: true
							},
							(res) => {
								if (!res) {
									setTimeout(() => {
										this.getElRect(elClass);
									}, 10);
									return;
								}
								this[dataVal] = res.height;
								resolve();
							}
						)
						.exec();
				});
			},
			// 右边菜单滚动  如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
			async rightScroll(e) {
				this.oldScrollTop = e.detail.scrollTop;
				if (this.arr.length == 0) {
					await this.getMenuItemTop();
				}
				if (this.timer) return;
				if (!this.menuHeight) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
				}
				setTimeout(() => {
					// 节流
					this.timer = null;
					let scrollHeight = e.detail.scrollTop + 90;
					const mainHeight = parseInt(this.mainHeight.split('px')[0]);
					// console.log(scrollHeight, mainHeight, e.detail.scrollHeight);
					if (scrollHeight + mainHeight >= e.detail.scrollHeight) {
						this.leftMenuStatus(this.arr.length - 1);
						return;
					}
					for (let i = 0; i < this.arr.length; i++) {
						let height1 = this.arr[i];
						let height2 = this.arr[i + 1];
						if (!height2 || (scrollHeight >= height1 && scrollHeight < height2)) {
							this.leftMenuStatus(i);
							break;
							return;
						}
					}
				}, 50);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.border-le {
		position: absolute;
		height: 30rpx;

		top: 50%;
		transform: translateY(-50%);
		left: 15rpx;
	}

	.class-content {
		margin-top: 185rpx;
	}

	.main {
		height: calc(100vh - env(safe-area-inset-bottom)); // 更安全的计算方式
		overflow: hidden;
		background-color: #f9f9f9;
		background-attachment: fixed;
		background-image: url('/static/main/Rectangle1.png');
		background-repeat: no-repeat;
		background-size: 100%;
	}

	.picker-search {
		box-sizing: border-box;
		padding: 20rpx 30rpx;
	}

	.brand-at {
		border: 1px #1677ff solid;
		color: #1677ff;
	}

	.scroll-container {
		width: 100%;
		height: 400rpx;
	}

	.right-top {
		width: calc(100vw - 200rpx);
		background-color: #fff;
		height: 70rpx;
		display: flex;
		align-items: center;

		.top {
			width: calc(100vw - 200rpx);
			display: flex;
			margin-left: 40rpx;
			position: absolute;
			right: 0;
			top: 30rpx;


			justify-content: space-around;
			padding-right: 20rpx;
			color: #777777;

			.top-for {
				display: flex;
				align-items: center;


			}

			text {
				margin-right: 8rpx;
			}
		}
	}

	.confrim {
		width: 550rpx;
		margin: 20rpx 20rpx;
		margin-top: 150rpx;

		.confrim-brand {
			.brand-name {
				font-weight: bold;
			}

			.brand-list {
				margin-top: 30rpx;
				display: flex;
				flex-wrap: wrap;

				text {
					display: block;
					width: 150rpx;
					height: 80rpx;
					background-color: #f3f3f3;
					margin-right: 20rpx;
					margin-bottom: 30rpx;
					text-align: center;
					line-height: 80rpx;
				}
			}
		}

		.price {
			margin: 30rpx 0;
			display: flex;
			align-items: center;

			input {
				background-color: #f3f3f3;
				width: 200rpx;
				height: 80rpx;
				text-align: center;
			}

			span {
				margin: 0 10rpx;
			}
		}

		.confrim-btn {
			display: flex;
			align-items: center;
			justify-content: space-evenly;

			.botton {
				margin-top: 200rpx;
				width: 200rpx;
				border-radius: 50rpx;
				font-weight: bold;
				font-size: 30rpx;
				background-color: #ebf3ff;
				color: #1677ff;
			}
		}
	}

	.container {
		overflow: auto;
		display: flex;
		height: 90%;
		background-color: white;
		border-radius: 60rpx;
		position: relative;

		.nav-menu {
			width: 200rpx;
			min-height: 620rpx;

			.menu-item {
				width: 200rpx;
				position: relative;
				height: 100rpx;
				box-sizing: border-box;
				line-height: 100rpx;
				text-align: center;
			}
		}

		.nav-content {
			flex: 1;
			min-height: 620rpx;
			padding-bottom: 400rpx;

			.body-list {
				margin-top: 35rpx;
				margin: 30rpx;
			}

			.orderInfo {
				width: 100%;
				box-sizing: border-box;
				display: flex;
				padding: 20rpx;
				border-radius: 10rpx;
				background-color: #fff;

				.info {
					display: flex;
					flex-direction: column;
					justify-content: space-around;
				}

				.infoname {
					display: flex;
					align-items: center;

					.tag {
						width: 64rpx;
						height: 36rpx;
						line-height: 36rpx;
						text-align: center;
						color: #1677ff;
						background-color: #deecff;
						border-radius: 25px;
						font-size: 20rpx;
						margin-right: 8rpx;
					}

					.name {
						font-size: 28rpx;
						width: 250rpx;
						display: -webkit-box;
						-webkit-line-clamp: 1;
						/* 限制为两行 */
						-webkit-box-orient: vertical;
						overflow: hidden;
						text-overflow: ellipsis;
					}

					.mode {
						width: 64rpx;
						height: 36rpx;
						line-height: 36rpx;
						text-align: center;
						color: #ff8662;
						border: 1px solid #ff8662;
						border-radius: 3px;
						font-size: 20rpx;
						margin-left: 15rpx;
					}
				}

				.Specifications {
					color: #777;
					font-size: 24rpx;
				}

				.price {
					display: flex;
					justify-content: space-between;

					.price-text {
						white-space: nowrap;
						font-weight: 600;
						color: red;
						margin-right: 20rpx;

						span {
							font-weight: 400;
							font-size: 22rpx;
						}
					}

					button {
						width: 128rpx;
						height: 42rpx;
						background: #1677ff;
						border-radius: 90rpx 90rpx 90rpx 90rpx;

						font-size: 20rpx;
						color: #ffffff;
						font-weight: 400;
						line-height: 42rpx;
					}
				}
			}
		}
	}

	.right {
		width: 73%;

		.null {
			text-align: center;
			width: 100%;
			height: 40rpx;
			line-height: 40rpx;
		}
	}
</style>